<?php

namespace AdminBundle\Controller;

use AdminBundle\Entity\BaseDevice;
use AdminBundle\Entity\BaseDeviceExtra;
use AdminBundle\Entity\BaseGroup;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use AdminBundle\Utility\Constant;

/**
 * Basedevice controller.
 *
 * @Route("basedevice")
 */
class BaseDeviceController extends Controller
{
    /**
     * Lists all baseDevice entities by group_id.
     *
     * @Route("/group/{id}/{has_default}", defaults={ "id"="0", "has_default" = ""}, name="basedevice_by_group")
     * @Method("GET")
     */
    public function deviceByGroupAction(Request $request, $id, $has_default)
    {
        $result = [];
        if ($has_default != "") {
            $result[] = ['key' => "", "value" => "全部"];
        }
        $baseDevices = $this->getDoctrine()->getRepository('AdminBundle:BaseDevice')->findBy(['groupId' => $id]);

        foreach ($baseDevices as $baseDevice) {
            $value = $baseDevice->getName() . ',' . $baseDevice->getImei();
            $result[] = ['key' => $baseDevice->getId(), 'value' => $value];
        }
        return $this->json($result);
    }

    /**
     * Lists all baseDevice entities.
     *
     * @Route("/", name="basedevice_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $page = $request->get("page");
        $page = is_numeric($page) ? $page : 1;
        $keyword = $request->get('keyword');
        $date_range = $request->get('date_range');
        $device_group = $request->get('device_group');
        if (!empty($date_range)) {
            $date_range = explode(" - ", $date_range);
            $starttime = $date_range[0];
            $endtime = $date_range[1];
        } else {
            $starttime = $endtime = null;
        }

        $starttime = date("Y-m-d", strtotime($starttime ?: "-3 day"));
        $endtime = date("Y-m-d", strtotime($endtime ?: "+1 day"));

        $params = ['keyword' => $keyword, 'starttime' => $starttime, 'endtime' => $endtime,
            'device_group' => $device_group];

        $em = $this->getDoctrine()->getManager();
        $result = $em->getRepository('AdminBundle:BaseDevice')->pageQuery($params, $page);

        $baseGroup = $em->getRepository('AdminBundle:BaseGroup')->findAll();
        $params['baseGroups'] = $baseGroup;

        return $this->render('AdminBundle:basedevice:index.html.twig', array_merge([
            'dataSources' => $result['list'],
            'querystring' => http_build_query($params),
            'page' => $result['page'],
        ], $params));
    }

    /**
     * Creates a new baseDevice entity.
     *
     * @Route("/new", name="basedevice_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $baseDevice = new Basedevice();
        $form = $this->createForm('AdminBundle\Form\BaseDeviceType', $baseDevice, Constant::FORM_ATTR_CLASS);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $baseDevice->setCtime(new \DateTime())
                ->setCreator($this->getUser()->getUsername())
                ->setIp($request->getClientIp());

            $groupId = 0;
            $groupName = '';
            if (($baseGroup = $form->getNormData()->getGroupId()) instanceof BaseGroup) {
                $groupId = $baseGroup->getId();
                $groupName = $baseGroup->getName();
            }

            $baseDevice->setGroupId($groupId);
            $baseDevice->setGroupName($groupName);

            $em = $this->getDoctrine()->getManager();
            $em->persist($baseDevice);
            $em->flush();
            // 新增额外信息
            $baseDeviceExtra = $em->getRepository('AdminBundle:BaseDeviceExtra')->find($baseDevice->getId());
            if ($baseDeviceExtra == null) {
                $baseDeviceExtra = new BaseDeviceExtra();
            }
            $baseDeviceExtra->setId($baseDevice->getId());
            $baseDeviceExtra->setInnerIp('0.0.0.0');
            $baseDeviceExtra->setOuterIp($request->getClientIp());
            $baseDeviceExtra->setLastRequestIp($request->getClientIp());
            $baseDeviceExtra->setLastReportTime(new \DateTime());
            $baseDeviceExtra->setLastRequestTime(new \DateTime());

            $em->persist($baseDeviceExtra);
            $em->flush();

            return $this->redirectToRoute('basedevice_show', array('id' => $baseDevice->getId()));
        }

        return $this->render('AdminBundle:basedevice:new.html.twig', array(
            'baseDevice' => $baseDevice,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a baseDevice entity.
     *
     * @Route("/{id}", name="basedevice_show")
     * @Method("GET")
     */
    public function showAction(BaseDevice $baseDevice)
    {
        $deleteForm = $this->createDeleteForm($baseDevice);

        return $this->render('AdminBundle:basedevice:show.html.twig', array(
            'dataSource' => $baseDevice,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing baseDevice entity.
     *
     * @Route("/{id}/edit", name="basedevice_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, BaseDevice $baseDevice)
    {
        $deleteForm = $this->createDeleteForm($baseDevice);
        $editForm = $this->createForm('AdminBundle\Form\BaseDeviceType', $baseDevice, Constant::FORM_ATTR_CLASS);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $form = $editForm;
            $groupId = 0;
            $groupName = '';
            if (($baseGroup = $form->getNormData()->getGroupId()) instanceof BaseGroup) {
                $groupId = $baseGroup->getId();
                $groupName = $baseGroup->getName();
            }

            $baseDevice->setGroupId($groupId);
            $baseDevice->setGroupName($groupName);

            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('basedevice_edit', array('id' => $baseDevice->getId()));
        }
        //设置select 对应属性默认值
        $em = $this->getDoctrine()->getManager();
        if ($baseDevice->getGroupId()) {
            $baseGroup = $em->getRepository('AdminBundle:BaseGroup')->findOneById($baseDevice->getGroupId());
            $editForm->get('groupId')->setData($baseGroup);
        }

        return $this->render('AdminBundle:basedevice:edit.html.twig', array(
            'dataSource' => $baseDevice,
            'form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a baseDevice entity.
     *
     * @Route("/{id}", name="basedevice_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, BaseDevice $baseDevice)
    {
        $form = $this->createDeleteForm($baseDevice);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($baseDevice);
            $em->flush();
        }

        return $this->redirectToRoute('basedevice_index');
    }

    /**
     * Creates a form to delete a baseDevice entity.
     *
     * @param BaseDevice $baseDevice The baseDevice entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(BaseDevice $baseDevice)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('basedevice_delete', array('id' => $baseDevice->getId())))
            ->setMethod('DELETE')
            ->getForm();
    }
}
